import streamlit as st
import os

class ConfigFilesView:
    """配置文件视图类"""
    
    def __init__(self):
        # Get the project root directory (parent of views directory)
        current_dir = os.path.dirname(os.path.abspath(__file__))
        project_root = os.path.dirname(current_dir)
        
        # Use absolute paths
        self.mail_conf_file = os.path.join(project_root, "conf", "mail_conf.txt")
        self.sheet_config_file = os.path.join(project_root, "conf", "sheet_config.txt")
    
    def render(self):
        """渲染配置文件页面"""
        st.markdown("<h1 class='main-header'>配置文件管理</h1>", unsafe_allow_html=True)
        
        # 使用标签页形式
        tab1, tab2 = st.tabs(["邮件配置", "字段配置"])
        
        with tab1:
            self._render_mail_config_tab()
        
        with tab2:
            self._render_sheet_config_tab()
    
    def _render_mail_config_tab(self):
        """渲染邮件配置标签页"""
        st.subheader("邮件配置文件 (mail_conf.txt)")
        
        try:
            with open(self.mail_conf_file, "r", encoding="utf-8") as f:
                mail_conf = f.read()
            
            with st.form("mail_conf_form"):
                mail_conf_edited = st.text_area("邮件配置内容", mail_conf, height=300)
                submitted = st.form_submit_button("保存邮件配置")
                
                if submitted:
                    with open(self.mail_conf_file, "w", encoding="utf-8") as f:
                        f.write(mail_conf_edited)
                    st.success("✅ 邮件配置已保存")
                    st.rerun()
        except Exception as e:
            st.error(f"❌ 读取邮件配置失败：{str(e)}")
    
    def _render_sheet_config_tab(self):
        """渲染字段配置标签页"""
        st.subheader("字段配置文件 (sheet_config.txt)")
        
        try:
            with open(self.sheet_config_file, "r", encoding="utf-8") as f:
                sheet_conf = f.read()
            
            with st.form("sheet_conf_form"):
                sheet_conf_edited = st.text_area("字段配置内容", sheet_conf, height=300)
                submitted = st.form_submit_button("保存字段配置")
                
                if submitted:
                    with open(self.sheet_config_file, "w", encoding="utf-8") as f:
                        f.write(sheet_conf_edited)
                    st.success("✅ 字段配置已保存")
                    st.rerun()
        except Exception as e:
            st.error(f"❌ 读取字段配置失败：{str(e)}")
    
    def _render_sheet_config_editor(self):
        """渲染字段配置文件编辑器"""
        st.subheader("📋 字段配置文件")
        
        # 读取文件内容
        sheet_content = ""
        if os.path.exists(self.sheet_config_file):
            try:
                with open(self.sheet_config_file, 'r', encoding='utf-8') as f:
                    sheet_content = f.read()
            except Exception as e:
                st.error(f"❌ 读取文件失败: {str(e)}")
        
        # 文件编辑器
        new_sheet_content = st.text_area(
            "字段配置内容",
            value=sheet_content,
            height=200,
            help="编辑Excel表格字段映射配置",
            key="sheet_config_editor"
        )
        
        col1, col2, col3 = st.columns([1, 1, 1])
        
        with col1:
            if st.button("💾 保存字段配置", type="primary", use_container_width=True):
                self._save_file(self.sheet_config_file, new_sheet_content, "字段配置")
        
        with col2:
            if st.button("🔄 重新加载 ", use_container_width=True):
                st.rerun()
        
        with col3:
            if os.path.exists(self.sheet_config_file):
                with open(self.sheet_config_file, 'r', encoding='utf-8') as f:
                    file_content = f.read()
                st.download_button(
                    "📥 下载文件 ",
                    data=file_content,
                    file_name="sheet_config.txt",
                    mime="text/plain",
                    use_container_width=True
                )
    
    def _save_file(self, file_path, content, file_type):
        """保存文件"""
        try:
            # 确保目录存在
            os.makedirs(os.path.dirname(file_path), exist_ok=True)
            
            # 保存文件
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            
            st.success(f"✅ {file_type}保存成功！")
            
        except Exception as e:
            st.error(f"❌ 保存{file_type}失败: {str(e)}")